<template>
  <div class="flex h-full">
    <a-card class="mr-2" :body-style="{ display: 'flex', flexDirection: 'column', height: '100%', padding: '12px 8px' }">
      <BaseTitle title="系统角色" />
      <PermissionsList ref="permissionsListRef" class="flex-1 overflow-auto" :row-data="{ status: 0 }" />
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <div class="flex flex-1 overflow-hidden">
        <a-card class="flex-1" :body-style="{ padding: '8px', overflow: 'hidden' }">
          <div class="flex justify-between items-center">
            <a-tabs v-model:active-key="activeAuthority" centered class="w-[400px]">
              <a-tab-pane :key="1" tab="操作权限" />
              <a-tab-pane :key="2" tab="数据权限" />
              <a-tab-pane :key="3" tab="报表权限" />
              <a-tab-pane :key="4" tab="BI权限" />
            </a-tabs>
            <div class="flex">
              <!-- <a-button style="margin: 0 8px" @click="getAuthorityMenu">重置</a-button> -->
              <a-button type="primary" @click="onClickSave">保存</a-button>
            </div>
          </div>
          <template v-if="activeAuthority === 1">
            <!-- 操作权限 -->
            <BaseTable
              :loading="loadingMenu"
              :data-source="dataSourceMenu"
              :row-selection="rowSelectionMenu"
              row-key="permissonCode"
              fill
              :columns="columnsMenu"
            >
              <template #expandIcon="{ expanded, record, onExpand }">
                <component
                  :is="expanded ? CaretDownOutlined : CaretRightOutlined"
                  v-if="record.children?.length > 0"
                  class="pl-1"
                  @click="onExpand(record, $event)"
                />
              </template>
            </BaseTable>
          </template>
          <!-- 数据权限 -->
          <div v-if="activeAuthority === 2" class="w-full">
            <BaseTable
              fill
              :loading="loadingData"
              :data-source="dataSourceData"
              row-key="permissonCode"
              :row-selection="rowSelectionData"
              :columns="columnsData"
            />
          </div>
          <!-- 报表权限 -->
          <div v-if="activeAuthority === 3" class="w-full">
            <BaseTable fill :loading="loadingReport" :data-source="dataSourceReport" row-key="id" :row-selection="rowSelectionReport" :columns="columnsReport">
              <template #expandIcon="{ expanded, record, onExpand }">
                <component
                  :is="expanded ? CaretDownOutlined : CaretRightOutlined"
                  v-if="record.children?.length > 0"
                  class="pl-1"
                  @click="onExpand(record, $event)"
                />
              </template>
            </BaseTable>
          </div>
          <!-- BI权限 -->
          <div v-if="activeAuthority === 4" class="w-full">
            <!-- <div class="flex items-center pb-2">
              <div><a-input v-model:value="BIName" placeholder="指标名称"  /></div>
              <div class="ml-4">
                <a-radio-group>
                  <a-radio :value="1">全部</a-radio>
                  <a-radio :value="2">数字指标</a-radio>
                  <a-radio :value="3">数据图表</a-radio>
                </a-radio-group>
              </div>
            </div> -->
            <a-form class="flex items-center">
              <a-form-item>
                <a-input v-model:value="BIFormState.biName" allow-clear placeholder="指标名称" @keyup.enter="getAuthorityBI" />
              </a-form-item>
              <a-form-item class="ml-4">
                <a-radio-group v-model:value="BIFormState.style" @change="getAuthorityBI">
                  <a-radio value="">全部</a-radio>
                  <a-radio value="1">数字指标</a-radio>
                  <a-radio value="2">数据图表</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-form>
            <BaseTable fill :loading="loadingBI" :data-source="dataSourceBI" row-key="permissonCode" :row-selection="rowSelectionBI" :columns="columnsBI">
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'outOrder'">
                  <EditCell> <a-input v-model:value="record.outOrder" placeholder="请输入" @blur="onBlurInput(record)" /></EditCell>
                </template>
              </template>
            </BaseTable>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { uniq } from 'lodash-es'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import PermissionsList from '../components/PermissionsList'
import useStore from '../store'

const store = useStore()
const permissionsListRef = ref()
const activeAuthority = ref(1)
const BIFormState = ref({
  biName: '',
  style: ''
})
const checkedKeysMenu = ref([])
const checkedKeysBI = ref([])
const checkedKeysData = ref([])
const checkedKeysReport = ref([])
const columnsMenu = ref([
  {
    title: '菜单名称',
    dataIndex: 'menuName'
  },
  {
    title: '权限代码',
    dataIndex: 'permissonCode'
  },
  {
    title: '菜单类型',
    dataIndex: 'menuType',
    customRender: ({ text }) => {
      return ['模块', '目录', '菜单', '按钮'][text - 1]
    }
  }
])
const columnsData = ref([
  {
    title: '权限名称',
    dataIndex: 'permissonName'
  },
  {
    title: '权限代码',
    dataIndex: 'permissonCode'
  }
])
const columnsReport = ref([
  {
    title: '报表名称',
    dataIndex: 'label'
  },
  {
    title: '权限代码',
    dataIndex: 'id'
  }
])
const columnsBI = ref([
  {
    title: '指标名称',
    dataIndex: 'permissonName'
  },
  {
    title: '单位',
    dataIndex: 'unit',
    width: 180
  },
  {
    title: '指标样式',
    dataIndex: 'style',
    width: 180
  },
  {
    title: '输出顺序',
    dataIndex: 'outOrder',
    width: 180
  },
  {
    title: '指标代码',
    dataIndex: 'permissonCode'
  },
  {
    title: '指标含义',
    dataIndex: 'biDesc'
  }
])
//操作权限
const {
  loading: loadingMenu,
  tableData: dataSourceMenu,
  getData: getAuthorityMenu
} = useTable({
  url: '/operation/opex/getSystemMenuList',
  params: {},
  pagination: false,
  formatParams: () => {
    return {
      roleId: store.currentRole.id,
      isxz: 0
    }
  },
  onSuccess: (data) => {
    checkedKeysMenu.value = findIdsWithChecked(data)
  }
})
//数据权限
const {
  loading: loadingData,
  tableData: dataSourceData,
  getData: getAuthorityData
} = useTable({
  url: '/operation/opex/getSystemDataPermissionsList',
  formatParams: () => ({ roleId: store.currentRole.id }),
  formatResult: (data) => {
    checkedKeysData.value = data.filter((item) => item.isXZ).map((item) => item.permissonCode)
    return data
  }
})
//报表权限
const {
  loading: loadingReport,
  tableData: dataSourceReport,
  getData: getAuthorityReport
} = useTable({
  url: '/ufs/report/getReportList',
  params: { pageNum: 1, pageSize: 1000 },
  pagination: false,
  formatResult: (data) => groupByKey(data),
  onSuccess: (data) => getReportAuthority(data)
})
//BI权限
const {
  loading: loadingBI,
  tableData: dataSourceBI,
  getData: getAuthorityBI
} = useTable({
  url: '/common/portal/getDictPermissionBiList',
  formatParams: () => ({ ...BIFormState.value, roleId: store.currentRole.id }),
  pagination: false,
  formatResult: (data) => {
    checkedKeysBI.value = data.filter((item) => item.isXZ).map((item) => item.permissonCode)
    return data
  }
  // onSuccess: (data) => getBIAuthority(data)
})
//获取保存的权限
const getReportAuthority = async (reportList) => {
  const { data, code, msg } = await post('/operation/opex/getSystemDataReportFormPermissionsList', {
    permissonType: 3,
    roleId: store.currentRole.id
  })
  if (code !== 0) return message.error(msg)
  const permissonCodes = data.map((item) => item.permissonCode)
  const reportListCodes = reportList.map((item) => item.id)
  checkedKeysReport.value = reportListCodes.filter((item) => permissonCodes.includes(item))
}
const groupByKey = (reports) => {
  const groupedReports = {}
  reports.forEach((report) => {
    const categoryId = report.categoryId
    const categoryName = report.categoryName
    if (!groupedReports[categoryId]) {
      groupedReports[categoryId] = {
        path: '/report?categoryId=' + categoryId,
        label: categoryName,
        categoryId,
        id: categoryId,
        children: []
      }
    }
    groupedReports[categoryId].children.push({
      id: report.id,
      categoryId: report.categoryId,
      path: `/report?categoryId=${categoryId}&id=${report.id}`,
      label: report.reportName,
      meta: report
    })
  })
  return Object.values(groupedReports)
}
//递归获取所有子节点children获取id
const getChildrenIds = (data, code) => {
  const arr = []
  data.forEach((item) => {
    arr.push(item[code])
    if (item.children) {
      arr.push(...getChildrenIds(item.children, code))
    }
  })
  return arr
}
const rowSelectionMenu = {
  checkStrictly: true,
  selectedRowKeys: checkedKeysMenu,
  onSelectAll: (selected) => {
    if (selected) {
      checkedKeysMenu.value = getChildrenIds(dataSourceMenu.value, 'permissonCode')
    } else {
      checkedKeysMenu.value = []
    }
  },
  onSelect: (record, selected) => {
    const permissonCodeMenu = getChildrenIds([record], 'permissonCode')
    if (selected) {
      checkedKeysMenu.value = uniq([...checkedKeysMenu.value, ...permissonCodeMenu])
    } else {
      checkedKeysMenu.value = checkedKeysMenu.value.filter((item) => !permissonCodeMenu.includes(item))
    }
  }
}
const rowSelectionBI = ref({
  checkStrictly: true,
  selectedRowKeys: checkedKeysBI,
  onChange: (selectedRowKeys) => {
    checkedKeysBI.value = selectedRowKeys
  }
})

const rowSelectionReport = {
  checkStrictly: false,
  selectedRowKeys: checkedKeysReport,
  onSelectAll: (selected) => {
    if (selected) {
      checkedKeysReport.value = getChildrenIds(dataSourceReport.value, 'id')
    } else {
      checkedKeysReport.value = []
    }
  },
  onSelect: (record, selected) => {
    const permissonCodeReport = getChildrenIds([record], 'id')
    if (selected) {
      checkedKeysReport.value = uniq([...checkedKeysReport.value, ...permissonCodeReport])
    } else {
      checkedKeysReport.value = checkedKeysReport.value.filter((item) => !permissonCodeReport.includes(item))
    }
  }
}

const rowSelectionData = ref({
  checkStrictly: true,
  selectedRowKeys: checkedKeysData,
  onChange: (selectedRowKeys) => {
    checkedKeysData.value = selectedRowKeys
  }
})
const getData = () => {
  getAuthorityMenu()
  getAuthorityData()
  getAuthorityReport()
  getAuthorityBI()
}

//获取所有选中的树结构并返回id数组
const findIdsWithChecked = (treeData) => {
  return treeData.reduce((accumulator, current) => {
    if (current.isXZ === 1) {
      accumulator.push(current.permissonCode)
    }
    if (current.children && current.children.length > 0) {
      const childIds = findIdsWithChecked(current.children)
      accumulator.push(...childIds)
    }
    return accumulator
  }, [])
}
const onClickSave = async () => {
  store.roleAdd = 0
  const { code, msg } = await post(
    '/operation/opex/doSaveRolePermission',
    {
      roleId: store.currentRole.id,
      operationPermissions: {
        permissonType: 1,
        permissonCode: checkedKeysMenu.value
      },
      dataPermissions: {
        permissonType: 2,
        permissonCode: checkedKeysData.value
      },
      reportPermissions: {
        permissonType: 3,
        permissonCode: checkedKeysReport.value
      },
      biPermissions: {
        permissonType: 4,
        permissonCode: checkedKeysBI.value
      }
    },
    {
      loading: true
    }
  )
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}
const onBlurInput = async (record) => {
  const { code, msg } = await post('/common/portal/doUpdateDictPermissionBi', {
    biCode: record.permissonCode,
    outOrder: record.outOrder
  })
  if (code !== 0) return message.error(msg)
  getAuthorityBI()
}
watch(
  () => store.currentRole.id,
  (val) => val && getData(),
  {
    immediate: true
  }
)
</script>
<style lang="less" scoped>
:deep(.ant-radio-button-wrapper) {
  padding: 0 25px;
}
:deep(.ant-table-row-level-1) {
  .ant-table-cell-with-append {
    ::after {
      position: absolute;
      top: 0;
      left: -48px;
      z-index: 999;
      width: 2px;
      height: 102%;
      border-left: 2px solid var(--primary-color);
      content: '';
    }
  }
}
:deep(.ant-table-row-level-2) {
  .ant-table-cell-with-append {
    ::after {
      position: absolute;
      top: 0;
      left: -48px;
      z-index: 999;
      width: 2px;
      height: 102%;
      // border-bottom: 2px solid var(--primary-color);
      border-left: 2px solid red;
      content: '';
    }
  }
}
.ant-tabs {
  :deep(.ant-tabs-nav-wrap) {
    justify-content: start !important;
  }
}
</style>
